package cn.zzuli.security.filter;

import cn.zzuli.security.security.TokenManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Date: 2021/1/2 18:59
 * @Author: 绯色下午茶
 * @Description:
 */
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;


    public TokenAuthenticationFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;

    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

//        获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken authRequest = getAuthication(request);
//       如果这个有权限信息，将权限放在上下文中
        if (authRequest != null) {
            SecurityContextHolder.getContext().setAuthentication(authRequest);

        }
    }

    private UsernamePasswordAuthenticationToken getAuthication(HttpServletRequest request) {
//        从header获取token
        String token = request.getHeader("token");
        if (token != null) {
//            从token获取用户名
            String username = tokenManager.getUserInfoFromToken(token);
//            从redis获取用户权限列表
            List<String> permissionValueList = (List<String>) redisTemplate.opsForValue().get(username);
//            改变参数类型
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            permissionValueList.forEach(per -> {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(per);
                authorities.add(authority);
            });

            return new UsernamePasswordAuthenticationToken(username, token, authorities);
        }
        return null;
    }
}
